<template>
  <div class="publicAccount">
    <block>
      <div class="item-title">公众号被关注回复（用户进入公众号）</div>
      <Form :model="formItem" :label-width="100" class="shopForm">
        <FormItem label="自动回复内容">
          <RadioGroup v-model="formItem.reply_type">
            <Radio label="text">回复纯文本</Radio>
            <Radio label="miniprogram">回复小程序卡片</Radio>
            <Radio label>不回复内容</Radio>
          </RadioGroup>
        </FormItem>
        <div v-if="formItem.reply_type == 'miniprogram'" class="follow-content flex">
          <div>
            <FormItem label="小程序卡片路径">
              <Select
                v-model="formItem.miniprogram_page_path"
                style="width:120px"
                @on-change="change(item.value,'miniprogram_page_path')"
              >
                <Option
                  v-for="(item,index) in pathList"
                  :key="index"
                  :value="item.path"
                >{{item.name}}</Option>
              </Select>
              <Input
                v-model="formItem.miniprogram_page_path"
                placeholder="请输入相应路径"
                style="width:400px"
              ></Input>
            </FormItem>
            <FormItem label="小程序卡片标题">
              <Input
                v-model="formItem.miniprogram_title"
                placeholder="请输入小程序卡片标题"
                style="width:200px"
              ></Input>
            </FormItem>
            <FormItem label="小程序卡片图片">
              <div v-if="formItem.miniprogram_page_thumb_url" class="brand-item-logo disFlex">
                <img :src="formItem.miniprogram_page_thumb_url" />
                <upload :multiple="true" :spread="true" @confirmUpload="changeLogoFn"></upload>
              </div>
              <div
                v-else
                class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
                style="margin: 0;"
              >
                <span>+ 添加图片</span>
                <upload :multiple="true" :spread="true" @confirmUpload="changeLogoFn"></upload>
              </div>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="confirm(0)">保存</Button>
            </FormItem>
          </div>
          <!-- <img
            class="img-demo-reply-miniprogram"
            :src="formItem.guide_message.remind_image_miniprogram"
            alt
          >-->
        </div>
        <div v-if="formItem.reply_type == 'text'" class="follow-content flex">
          <div>
            <FormItem label="自动回复内容" prop="text_content">
              <div class="flex column start">
                <div style="margin-bottom: 15px;">
                  <Button type="primary" @click="showAddMiniprogram(0)">添加小程序链接</Button>
                </div>
                <Input
                  id="replyText"
                  type="textarea"
                  style="width: 35rem;"
                  :rows="10"
                  v-model="formItem.text_content"
                  placeholder="自动回复内容"
                ></Input>
                <p style="color: gray;">
                  文案内容如果包含粉丝昵称，请用
                  <span style="color:red;">{nickname}</span> 代替
                </p>
                <p style="color: gray;">{{formItem.guide_message.notify}}</p>
              </div>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="confirm(0)">保存</Button>
            </FormItem>
          </div>
          <div class="disFlex vertical">
            <p class="demo-title">消息预览</p>
            <div class="preview-wrapper disFlex">
              <img :src="formItem.guide_message.remind_image_text" alt />
              <p v-html="reply_text_html"></p>
            </div>
            <!-- <p class="demo-title">示意</p>
            <img class="img-demo-reply-text" :src="formItem.guide_message.remind_image_text" alt>-->
          </div>
        </div>
        <FormItem v-if="formItem.reply_type == ''">
          <Button type="primary" @click="confirm(0)">保存</Button>
        </FormItem>
      </Form>
    </block>
    <block>
      <div class="item-title" style="display:flex;">
        公众号打开回复（用户进入公众号）
        <div style="font-weight:normal">
          使用此功能的服务号必须开启
          <span
            style="padding: 2px 4px;font-size: 90%;color: #c7254e;background-color: #f9f2f4;border-radius: 4px;"
          >获取用户地理位置</span>的接口权限，
          <Poptip
            placement="right"
            trigger="hover"
            word-wrap
            width="200"
            content="登录微信公众平台，点击左侧菜单【开发 / 接口权限】，找到类目中的【对话服务 / 用户管理 / 获取用户地理位置】，点击开启按钮并配置为每次上报"
          >
            <div class="flex center">
              <div
                style="margin-right:3px;font-size:10px;border-radius:7px; background: #2d8cf0; width:14px;height:14px;text-align:center;line-height:16px;color:white;"
              >?</div>
              <a href="javascript:">如何开启</a>
            </div>
          </Poptip>
        </div>
      </div>
      <Form :model="formAuto" :label-width="100" class="shopForm">
        <FormItem label="自动回复内容">
          <div class="flex column">
            <RadioGroup v-model="formAuto.reply_type">
              <Radio label="text">回复纯文本</Radio>
              <Radio label="miniprogram">回复小程序卡片</Radio>
              <Radio label>不回复内容</Radio>
            </RadioGroup>
            <span v-if="formAuto.reply_type=='text'" style="color:#6F6C6C;">
              用户进公众号就会收到自动回复的小程序链接
              <span style="color: red;margin-left: 10px;">24小时内重复进入只发1次</span>
            </span>
          </div>
        </FormItem>
        <div v-if="formAuto.reply_type == 'miniprogram'" class="follow-content flex">
          <div>
            <FormItem label="小程序卡片路径">
              <Select
                v-model="formAuto.miniprogram_page_path"
                style="width:120px"
                @on-change="change(item.value,'miniprogram_page_path')"
              >
                <Option
                  v-for="(item,index) in pathList"
                  :key="index"
                  :value="item.path"
                >{{item.name}}</Option>
              </Select>
              <Input
                v-model="formAuto.miniprogram_page_path"
                placeholder="请输入相应路径"
                style="width:400px"
              ></Input>
            </FormItem>
            <FormItem label="小程序卡片标题">
              <Input
                v-model="formAuto.miniprogram_title"
                placeholder="请输入小程序卡片标题"
                style="width:200px"
              ></Input>
            </FormItem>
            <FormItem label="小程序卡片图片">
              <div v-if="formAuto.miniprogram_page_thumb_url" class="brand-item-logo disFlex">
                <img :src="formAuto.miniprogram_page_thumb_url" />
                <upload :multiple="true" :spread="true" @confirmUpload="changeLogoGong"></upload>
              </div>
              <div
                v-else
                class="brand-item-environment new-add-brand-item-environment disFlex Flex-middle Flex-center"
                style="margin: 0;"
              >
                <span>+ 添加图片</span>
                <upload :multiple="true" :spread="true" @confirmUpload="changeLogoGong"></upload>
              </div>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="confirm(1)">保存</Button>
            </FormItem>
          </div>
          <!-- <img
            class="img-demo-reply-miniprogram"
            :src="formAuto.guide_message.remind_image_miniprogram"
            alt
          >-->
        </div>
        <div v-if="formAuto.reply_type == 'text'" class="follow-content flex">
          <div>
            <FormItem label="自动回复内容" prop="text_content">
              <div class="flex column start">
                <div style="margin-bottom: 15px;">
                  <Button type="primary" @click="showAddMiniprogram(1)">添加小程序链接</Button>
                </div>
                <Input
                  id="replyTextAuto"
                  type="textarea"
                  style="width: 35rem;"
                  :rows="10"
                  v-model="formAuto.text_content"
                  placeholder="自动回复内容"
                ></Input>
                <p style="color: gray;">
                  文案内容如果包含粉丝昵称，请用
                  <span style="color:red;">{nickname}</span> 代替
                </p>
                <p style="color: gray;">{{formAuto.guide_message.notify}}</p>
              </div>
            </FormItem>
            <FormItem>
              <Button type="primary" @click="confirm(1)">保存</Button>
            </FormItem>
          </div>
          <div class="disFlex vertical">
            <p class="demo-title">消息预览</p>
            <div class="preview-wrapper disFlex">
              <img :src="formAuto.guide_message.remind_image_text" alt />
              <p v-html="reply_text_htmlAuto"></p>
            </div>
            <!-- <p class="demo-title">示意</p>
            <img class="img-demo-reply-text" :src="formAuto.guide_message.remind_image_text" alt>-->
          </div>
        </div>
        <FormItem v-if="formAuto.reply_type == ''">
          <Button type="primary" @click="confirm(1)">保存</Button>
        </FormItem>
      </Form>
    </block>
    <!-- 添加小程序链接弹框 -->
    <Modal v-model="showAddMiniprogramLink">
      <p slot="header" style="color:rgb(8, 93, 196);text-align:center">
        <span>添加小程序链接</span>
      </p>
      <div class="model-miniprogram-wrapper">
        <Form
          ref="modelMiniprogram"
          :label-width="120"
          :model="modelMiniprogram"
          :rules="modelMiniprogramRule"
          label-position="left"
        >
          <FormItem label="小程序卡片路径" prop="miniprogram_path">
            <div class="flex center">
              <Select v-model="modelMiniprogram.miniprogram_path" class="select-wrapper">
                <Option
                  v-for="(item,index) in pathList"
                  :key="index"
                  :value="item.path"
                >{{item.name}}</Option>
              </Select>
              <Input
                style="width: 250px;"
                readonly
                v-model="modelMiniprogram.miniprogram_path"
                @click.native="tapModelInput"
                placeholder="请选择跳转路径"
              ></Input>
            </div>
          </FormItem>
          <FormItem label="链接文案" prop="link_title">
            <Input
              style="width: 300px;"
              v-model="modelMiniprogram.link_title"
              placeholder="小程序卡片标题"
            ></Input>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <div class="flex center column-center">
          <Button @click="showAddMiniprogramLink=false">取消</Button>
          <Button type="primary" @click="saveModal">保存</Button>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script>
import upload from "base/upload/upload";
import { SubscribeConfig, SubscribeConfigUpdate } from "api/recuit/setting";

export default {
  name: "publicAccount",
  data() {
    return {
      formItem: {
        worker_avatar: "",
        type: "1",
        input: ""
      },
      formAuto: {},
      showAddMiniprogramLink: false,
      // 添加小程序链接表单规则
      modelMiniprogramRule: {
        miniprogram_path: [
          { required: true, message: "小程序链接不能为空", trigger: "change" }
        ],
        link_title: [
          { required: true, message: "小程序链接文案不能为空", trigger: "blur" }
        ]
      },
      // 添加小程序链接表单
      modelMiniprogram: {
        // 路径类型
        miniprogram_type: 0,
        // 跳转路径
        miniprogram_path: "pages/consumer/index/index",
        // 链接文案
        link_title: ""
      },
      pathList: [
        {
          name: "用户端-首页",
          path: "pages/consumer/index/index"
        },
        {
          name: "企业端-首页",
          path: "pages/business/index/index"
        }
      ]
    };
  },
  components: {
    upload
  },
  computed: {
    reply_text_html: function() {
      let str = this.formItem.text_content
        .replace(/\r\n/g, "<br/>")
        .replace(/\n/g, "<br/>");
      return str;
    },
    reply_text_htmlAuto: function() {
      let str = this.formAuto.text_content
        .replace(/\r\n/g, "<br/>")
        .replace(/\n/g, "<br/>");
      return str;
    }
  },
  mounted() {
    //关注回复
    this.getData({ isAutoConfig: 0 });
    //自动回复
    this.getData({ isAutoConfig: 1 });
  },
  methods: {
    // 改变logo图片
    changeLogoFn(_url) {
      this.formItem.miniprogram_page_thumb_url = _url[0];
    },
    // 改变公众号logo图片
    changeLogoGong(_url) {
      this.formAuto.miniprogram_page_thumb_url = _url[0];
    },
    change(value, key) {
      this.formItem[key] = value;
    },
    // 小程序链接卡片路径类型切换
    choseMiniprogramType() {
      this.modelMiniprogram.miniprogram_path = "app/mallA/index/index";
    },
    // 保存弹框添加小程序链接内容
    saveModal() {
      this.$refs.modelMiniprogram.validate(valid => {
        if (valid) {
          this.showAddMiniprogramLink = false;
          if (this.isAutoConfig == 0) {
            var title = `<a data-miniprogram-appid="${this.formItem.wechat_app_id}" data-miniprogram-path="${this.modelMiniprogram.miniprogram_path}"  href="http://">${this.modelMiniprogram.link_title}</a>`;
            this.addCursor(
              document.getElementById("replyText").children[0],
              title
            );
          } else if (this.isAutoConfig == 1) {
            var title = `<a data-miniprogram-appid="${this.formAuto.wechat_app_id}" data-miniprogram-path="${this.modelMiniprogram.miniprogram_path}"  href="http://">${this.modelMiniprogram.link_title}</a>`;
            this.addCursor(
              document.getElementById("replyTextAuto").children[0],
              title
            );
          }
        } else {
          this.$Message.error("请填写完整信息!");
        }
      });
    },
    // 获取光标位置
    getCursor(textarea) {
      var rangeData = { text: "", start: 0, end: 0 };
      if (textarea.setSelectionRange) {
        // W3C
        textarea.focus();
        rangeData.start = textarea.selectionStart;
        rangeData.end = textarea.selectionEnd;
        rangeData.text =
          rangeData.start != rangeData.end
            ? textarea.value.substring(rangeData.start, rangeData.end)
            : "";
      } else if (document.selection) {
        // IE
        textarea.focus();
        var i,
          oS = document.selection.createRange(),
          // Don't: oR = textarea.createTextRange()
          oR = document.body.createTextRange();
        oR.moveToElementText(textarea);

        rangeData.text = oS.text;
        rangeData.bookmark = oS.getBookmark();

        // object.moveStart(sUnit [, iCount])
        // Return Value: Integer that returns the number of units moved.
        for (
          i = 0;
          oR.compareEndPoints("StartToStart", oS) < 0 &&
          oS.moveStart("character", -1) !== 0;
          i++
        ) {
          // Why? You can alert(textarea.value.length)
          if (textarea.value.charAt(i) == "\r") {
            i++;
          }
        }
        rangeData.start = i;
        rangeData.end = rangeData.text.length + rangeData.start;
      }
      return rangeData;
    },
    // 设置光标位置
    setCursor(textarea, rangeData) {
      var oR, start, end;
      textarea.focus();
      if (textarea.setSelectionRange) {
        // W3C
        textarea.setSelectionRange(rangeData.start, rangeData.end);
      } else if (textarea.createTextRange) {
        // IE
        oR = textarea.createTextRange();
        // Fixbug : ues moveToBookmark()
        // In IE, if cursor position at the end of textarea, the set function don't work
        if (textarea.value.length === rangeData.start) {
          //alert('hello')
          oR.collapse(false);
          oR.select();
        } else {
          oR.moveToBookmark(rangeData.bookmark);
          oR.select();
        }
      }
    },
    // 添加文字
    addCursor(textarea, text) {
      var oValue, nValue, oR, sR, nStart, nEnd, st;
      var rangeData = this.getCursor(textarea);
      this.setCursor(textarea, rangeData);

      if (textarea.setSelectionRange) {
        // W3C
        oValue = textarea.value;
        nValue =
          oValue.substring(0, rangeData.start) +
          text +
          oValue.substring(rangeData.end);
        nStart = nEnd = rangeData.start + text.length;
        st = textarea.scrollTop;
        textarea.value = nValue;
        if (this.isAutoConfig == 0) {
          this.formItem.text_content = nValue;
        } else if (this.isAutoConfig == 1) {
          this.formAuto.text_content = nValue;
        }
        // Fixbug:
        // After textarea.values = nValue, scrollTop value to 0
        if (textarea.scrollTop != st) {
          textarea.scrollTop = st;
        }
        textarea.setSelectionRange(nStart, nEnd);
      } else if (textarea.createTextRange) {
        // IE
        sR = document.selection.createRange();
        sR.text = text;
        if (this.isAutoConfig == 0) {
          this.formItem.text_content = text;
        } else if (this.isAutoConfig == 1) {
          this.formAuto.text_content = text;
        }
        sR.setEndPoint("StartToEnd", sR);
        sR.select();
      }
    },
    showAddMiniprogram(isAutoConfig) {
      this.isAutoConfig = isAutoConfig;
      this.showAddMiniprogramLink = true;
    },
    //保存数据
    confirm(isAutoConfig) {
      let data = {};
      if (isAutoConfig == 0) {
        this.formItem.isAutoConfig = isAutoConfig;
        data = this.formItem;
      } else if (isAutoConfig == 1) {
        this.formAuto.isAutoConfig = isAutoConfig;
        data = this.formAuto;
      }
      SubscribeConfigUpdate(data)
        .then(result => {
          this.$Message.success("保存成功");
        })
        .catch(err => {
          console.log(err);
        });
    },
    //获取数据
    getData({ isAutoConfig }) {
      SubscribeConfig({ isAutoConfig })
        .then(result => {
          if (isAutoConfig == 0) {
            this.formItem = result;
          } else if (isAutoConfig == 1) {
            this.formAuto = result;
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

<style scoped lang="less">
.publicAccount {
  width: 100%;
  height: 100%;
  padding: 2%;
  background: white;
  .item-title {
    margin-bottom: 20px;
    padding: 8px 16px;
    font-weight: bolder;
    background-color: #f5f5f5;
    color: #333;
  }
  .content {
    font-size: 14px;
    padding: 0 1% 1% 1%;
    a {
      color: rgb(143, 169, 211);
    }
  }
  .serviceConfirm {
    margin: 30px 30px 40px 800px;
  }
  .brand-item-logo {
    width: 100px;
    height: 100px;
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 5px;
    cursor: pointer;
    position: relative;
    top: 0;
    left: 0;

    img {
      width: 100%;
    }
  }
  .brand-item-environment {
    width: 214px;
    height: 120px;
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 5px;
    position: relative;
    top: 0;
    left: 0;
    margin-left: 15px;
    overflow: hidden;
    margin-top: 10px;

    &:nth-of-type(2n + 1) {
      margin-left: 0;
    }

    img {
      width: 100%;
      height: 100%;
      float: left;
    }

    & > .close {
      background: red;
      position: absolute;
      top: 0;
      right: 0;
      width: 20px;
      height: 20px;
      cursor: pointer;
      color: #fff;
    }
  }

  .old-brand-item-environment {
    margin-left: 0;
    cursor: pointer;
  }

  .new-add-brand-item-environment {
    padding: 5px;
    border: 1px solid #ddd;
    border-radius: 5px;
    position: relative;
    top: 0;
    left: 0;
    margin-left: 15px;
    overflow: hidden;
    margin-left: 15px;
    cursor: pointer;
    width: 100px;
    height: 100px;
    margin-top: 29px;

    &:nth-of-type(2n + 1) {
      margin-left: 0;
    }

    img {
      width: 100%;
      height: 100%;
      float: left;
    }

    & > .close {
      background: red;
      position: absolute;
      top: 0;
      right: 0;
      width: 20px;
      height: 20px;
      cursor: pointer;
      color: #fff;
    }
  }
  .demo-title {
    text-align: center;
    padding: 10px;
    color: black;
  }
  .follow-content {
    background: white;
    padding: 20px;
    padding-top: 0;
    justify-content: space-between;
  }
  .preview-wrapper {
    width: 370px;
    min-width: 370px;
    height: 200px;
    padding: 10px;
    background-color: rgb(233, 229, 233);
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-left: 20px;
  }

  .preview-wrapper img {
    width: 40px;
    min-width: 40px;
    height: 40px;
    background: gray;
    margin-right: 10px;
  }

  .preview-wrapper p {
    background: white;
    width: 230px;
    border-radius: 5px;
    padding: 10px;
    color: black;
    font-size: 16px;
    overflow-y: auto;
    word-wrap: break-word;
  }
  .img-demo-reply-text {
    display: inline-block;
    width: 370px;
    min-width: 370px;
    height: 270px;
    padding: 4px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-left: 20px;
  }
  .img-demo-reply-miniprogram {
    display: inline-block;
    width: 370px;
    min-width: 370px;
    height: 380px;
    padding: 4px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-left: 20px;
  }
}
.select-wrapper {
  width: 128px;
  margin-right: 15px;
}
</style>
